<?php
/**
 * CreateTime: 2022/6/24 14:47
 */

namespace App\Service\MapService;

use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Consts\TableConsts\TableConsts;
use App\Func\ResponseFunc;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\DB;

class TableMapService
{

    public function buildMapRelation(){
        return [
            TableConsts::CY_COMPANY_TABLE_NAME => [
                [
                    "relationTableName" => TableConsts::CY_DEPARTMENT_TABLE_NAME,
                    "relationTableKey" => 'department_id'
                ],
                [
                    "relationTableName" => TableConsts::CY_STAFF_TABLE_NAME,
                    "relationTableKey" => 'staff_id'
                ]
            ],
            TableConsts::CY_DEPARTMENT_TABLE_NAME => [
                [
                    "relationTableName" => TableConsts::CY_FULFILLMENT_TABLE_NAME,
                    "relationTableKey" => 'fulfillment_id'
                ],
                [
                    "relationTableName" => TableConsts::CY_CONTRACT_TABLE_NAME,
                    "relationTableKey" => 'contract_id'
                ]
            ],
            TableConsts::CY_CONTRACT_TABLE_NAME => [

            ],
            TableConsts::CY_FULFILLMENT_NODE_EXCEPTION_SOLVE_TABLE_NAME => [

            ],
        ];
    }

    public function returnTableMapRelationByTableName($id,$tableName){
        $buildMap = $this->buildMapRelation();
        if(!isset($buildMap[$tableName])){
            return true;
        }else{
            $buildMapTableInfo = $buildMap[$tableName];
            foreach($buildMapTableInfo as $checkerTable){
                if(isset($checkerTable["relationTableName"])){
                    $isExist = DB::table($checkerTable["relationTableName"])
                        ->where($checkerTable['relationTableKey'],$id)
                        ->first();
                    if($isExist){
                        throw new HttpResponseException( ResponseFunc::returnJson(
                            'error',
                            null,
                            '存在绑定关系不允许删除',
                            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                        ));
                    }
                    $this->returnTableMapRelationByTableName($id,$checkerTable["relationTableName"]);
                }
            }
        }
    }
}